﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Glucometer.ModuleHandler;
using System.Threading;

namespace Glucometer
{
    public class DeviceMemory
    {
        Queue<TestRecord> _recordMemory = new Queue<TestRecord>();

        public Queue<TestRecord> RecordMemory
        {
            get { return _recordMemory; }
        }

        public event d_EmptyArgument TransferCompleted;

        private int _browsePosition = 0;

        private int MAX_RECORD_COUNT = 30;

        public int getRecordMemoryCount()
        {
            return RecordMemory.Count;
        }

        public void initializeBrowsePositionToLatestRecord()
        {
            _browsePosition = getRecordMemoryCount() - 1;
        }

        public TestRecord browseLatestRecord()
        {
            return RecordMemory.ElementAt(getRecordMemoryCount() - 1);
        }

        public TestRecord browseLatestRecord(out int recordNumber)
        {
            recordNumber = getRecordMemoryCount();
            return browseLatestRecord();
        }

        public TestRecord getNextRecord(bool Backward)
        {
            _browsePosition = 
                (Backward) ? (_browsePosition + 1) % RecordMemory.Count :
                 (_browsePosition - 1 + RecordMemory.Count) % RecordMemory.Count;
            return RecordMemory.ElementAt(_browsePosition);
        }

        public TestRecord getNextRecord(bool Backward, out int recordNumber)
        {
            TestRecord rec = getNextRecord(Backward);
            recordNumber = _browsePosition + 1;
            return rec;
        }

        public void StartTransfer()
        {
            //START THE TRANSFERING HERE
            System.Threading.Thread.Sleep(1000);
            //WHEN THE TRANSFERING IS COMPLETE RAISE THE TRANSFER COMPLETE EVENT
            if (TransferCompleted != null)
                TransferCompleted();
        }

        public void addRecord(TestRecord record)
        {
            RecordMemory.Enqueue(record);
            if (RecordMemory.Count > MAX_RECORD_COUNT)
                RecordMemory.Dequeue();
        }

        public void ClearMemoryRecord()
        {
            _browsePosition = 0;
            RecordMemory.Clear();
        }

        internal void StopTransfer()
        {
            //throw new NotImplementedException();
        }
    }
}